package com.demo.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.module.commonui.R;
import com.tange.base.toolkit.DimenUtil;
import com.tange.base.toolkit.StringUtils;
import com.tg.appcommon.android.TGLog;

import java.util.ArrayList;


public class TGTabSwitchView extends LinearLayout {

    private static final int TEXT_WHITE = 0xFFFFFF;
    private static final int TEXT_GREEN = 0x82C23F;
    private ImageView mTabIvBg;

    private final ArrayList<View> viewList = new ArrayList<>();
    private ViewPager mViewPager;

    private TabEventListener mListener;
    private int itemTextColorNormal;
    private int itemTextColorPressed;
    private int tabWidth;
    LinearLayout mTabContent;
    private int mItemNum;
    private int curPageIndex = 0;
    public TGTabSwitchView(Context context) {
        this(context, null);
    }

    public TGTabSwitchView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TGTabSwitchView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initViews(context, attrs);
    }

    public int getCurPageIndex(){
        return curPageIndex;
    }

    public void setText(String itemText, Context context){
        if (!StringUtils.isEmpty(itemText)){
            String[] text = itemText.split(",");
            if (text.length != mItemNum){
                if (mTabContent.getChildCount() > 0){
                    mTabContent.removeAllViews();
                }
                if (viewList.size() > 0){
                    viewList.clear();
                }
                mItemNum = text.length;
                for (int i = 0; i < mItemNum; i++) {
                    TextView textView = new TextView(context);
                    textView.setText(text[i]);
                    textView.setTextColor(getColorSelector(itemTextColorNormal, itemTextColorPressed));
                    textView.setGravity(Gravity.CENTER);
                    textView.setOnClickListener(mOnClickListener);
                    textView.setTag(i);
                    viewList.add(textView);
                    LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    layoutParams.weight = 1;
                    layoutParams.width = DimenUtil.dp2px(context, 80);
                    textView.setLayoutParams(layoutParams);
                    mTabContent.addView(textView);
                }
                setSelect(viewList.get(0));
            }
        }
    }

    private void initViews(Context context, @Nullable AttributeSet attrs) {
        View view = View.inflate(context, R.layout.layout_tabs_switch, this);
        LinearLayout tabLayout = view.findViewById(R.id.ll_tab);
        FrameLayout tabBg =  view.findViewById(R.id.bg_tab);
        mTabIvBg =  view.findViewById(R.id.bg_iv_tab);
        mTabContent = view.findViewById(R.id.ll_tab_content);

        @SuppressLint("CustomViewStyleable") TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TGTabSwitchView);
        int layoutBackground = a.getResourceId(R.styleable.TGTabSwitchView_layoutBackground, android.R.color.white);
        int layoutPaddingLeft = a.getDimensionPixelSize(R.styleable.TGTabSwitchView_layoutPaddingLeft, 20);
        int layoutPaddingTop = a.getDimensionPixelSize(R.styleable.TGTabSwitchView_layoutPaddingTop, 20);
        int layoutPaddingRight = a.getDimensionPixelSize(R.styleable.TGTabSwitchView_layoutPaddingRight, 20);
        int layoutPaddingBottom = a.getDimensionPixelSize(R.styleable.TGTabSwitchView_layoutPaddingBottom, 20);
        int tabBackground = a.getResourceId(R.styleable.TGTabSwitchView_switch_Background, R.mipmap.bg_gray);
        int itemSelBg = a.getResourceId(R.styleable.TGTabSwitchView_itemSelBg, -1);
        mItemNum = a.getInteger(R.styleable.TGTabSwitchView_itemNum, 2);
        String itemText = a.getString(R.styleable.TGTabSwitchView_itemText);
        itemTextColorNormal = a.getColor(R.styleable.TGTabSwitchView_itemTextColorNormal, TEXT_GREEN);
        itemTextColorPressed = a.getColor(R.styleable.TGTabSwitchView_itemTextColorPressed, TEXT_WHITE);
        boolean isText =  a.getBoolean(R.styleable.TGTabSwitchView_isText, true);
        tabLayout.setBackgroundResource(layoutBackground);
        tabLayout.setPadding(layoutPaddingLeft, layoutPaddingTop, layoutPaddingRight, layoutPaddingBottom);
        tabBg.setBackgroundResource(tabBackground);
        if (itemSelBg != -1){
            mTabIvBg.setBackgroundResource(itemSelBg);
        }


        ViewGroup.LayoutParams lp = mTabIvBg.getLayoutParams();
        lp.width = DimenUtil.dp2px(context, 80);
        lp.height = DimenUtil.dp2px(context,40);
        mTabIvBg.setLayoutParams(lp);
        tabWidth = lp.width;

        if (isText && !StringUtils.isEmpty(itemText)){
            String[] text = itemText.split(",");
            for (int i = 0; i < mItemNum; i++) {
                TextView textView = new TextView(context);
                textView.setText(text[i]);
                textView.setTextColor(getColorSelector(itemTextColorNormal, itemTextColorPressed));
                textView.setGravity(Gravity.CENTER);
                textView.setOnClickListener(mOnClickListener);
                textView.setTag(i);
                viewList.add(textView);
                LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
                layoutParams.weight = 1;
                layoutParams.width = DimenUtil.dp2px(context, 80);
                textView.setLayoutParams(layoutParams);
                mTabContent.addView(textView);
            }
        }else {
            Drawable image_1 = a.getDrawable(R.styleable.TGTabSwitchView_switch_image_1);
            Drawable image_2 = a.getDrawable(R.styleable.TGTabSwitchView_switch_image_2);
            Drawable image_3 = a.getDrawable(R.styleable.TGTabSwitchView_switch_image_3);
            for (int i = 0; i < mItemNum; i++) {
                ImageView imageView = new ImageView(context);
                if (i == 0){
                    imageView.setImageDrawable(image_1);
                }else if (i == 1){
                    imageView.setImageDrawable(image_2);
                }else if (i == 2){
                    imageView.setImageDrawable(image_3);
                }
                imageView.setOnClickListener(mOnClickListener);
                imageView.setTag(i);
                viewList.add(imageView);
                LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.weight = 1;
                layoutParams.width = DimenUtil.dp2px(context, 80);
                layoutParams.gravity = Gravity.CENTER;
                imageView.setLayoutParams(layoutParams);
                mTabContent.addView(imageView);
                TGLog.d("ImageView = " + imageView);
            }
        }
        setSelect(viewList.get(0));
        a.recycle();
    }

    private final OnClickListener mOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            setSelect(v);
            int tag = (Integer) v.getTag();
            TGLog.d("tag = " + tag);
            mViewPager.setCurrentItem(tag);
            curPageIndex = tag;
            if (mListener != null) {
                mListener.onPageClick(tag);
            }
        }
    };


    public void setSelect(View tv) {
        for (View v : viewList) {
            TGLog.d("setSelected" + v + ", tv =" + tv);
            v.setSelected(v == tv);
        }
    }

    public void setViewPager(ViewPager viewPager) {
        if (viewPager != null) {
            mViewPager = viewPager;
            viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

                @Override
                public void onPageSelected(final int position) {
                    TGLog.d("onPageSelected : position = " + position);
                    curPageIndex = position;
                    if (mListener != null) {
                        mListener.onPageSelected(position);
                    }
                }

                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    TGLog.d("position = " + position + ", positionOffset = " + positionOffset);
                    if (positionOffset ==  0.0f){
                        View view =  viewList.get(position);
                        setViewState(positionOffset, view, true);

                        View view2 = viewList.get(0);
                        if (position < viewList.size()-1) {
                            view2 = viewList.get(position + 1);
                        }
                        setViewState(1 - positionOffset, view2, false);
                    }

                    mTabIvBg.setTranslationX(tabWidth * position + tabWidth * positionOffset);
                }

                @Override
                public void onPageScrollStateChanged(int state) {
                }
            });
        }
    }

    private void setViewState(float positionOffset, View view, boolean selected) {
        if (view instanceof TextView){
            ((TextView)view).setTextColor(evaluate(positionOffset, itemTextColorPressed, itemTextColorNormal));
        }else if (view instanceof ImageView){
            TGLog.d("onPageScrolled position = " + view);
            view.setSelected(selected);
        }
    }

    private ColorStateList getColorSelector(int normalColor, int pressedColor) {
        return new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_pressed},
                        new int[]{android.R.attr.state_selected},
                        new int[]{}
                },
                new int[]{
                        pressedColor,
                        pressedColor,
                        normalColor
                }
        );
    }

    public int evaluate(float fraction, int startValue, int endValue) {
        int startR = ((Integer) startValue >> 16) & 0xff;
        int startG = ((Integer) startValue >> 8) & 0xff;
        int startB = (Integer) startValue & 0xff;

        int endInt = (Integer) endValue;
        int endR = (endInt >> 16) & 0xff;
        int endG = (endInt >> 8) & 0xff;
        int endB = endInt & 0xff;

        return (int)((0xff) << 24) |
                (int)((startR + (int)(fraction * (endR - startR))) << 16) |
                (int)((startG + (int)(fraction * (endG - startG))) << 8) |
                (int)((startB + (int)(fraction * (endB - startB))));
    }

    public void setTabEventListener(TabEventListener listener) {
        mListener = listener;
    }

    public interface TabEventListener {
        void onPageSelected(int position);
        void onPageClick(int position);
    }
}
